import Vue from "vue";
import store from "../../store/index";
import { getToken,localstorageGetToken } from "../../utils/auth";
// import SocketBus from "./socketEventBus";
let socket = {
  websocket: null,
  // 连接地址
  ws_url: "",
  // 开启标识
  socket_open: false,
  // 心跳timer
  hearbeat_timer: null,
  // 心跳发送频率 240000
  hearbeat_interval: 240000,
  // 是否自动重连
  is_reonnect: true,
  // 重连次数
  reconnect_count: 5,
  // 已发起重连次数
  reconnect_current: 0,
  // 重连timer
  reconnect_timer: null,
  // 重连频率
  reconnect_interval: 3000,
  // 超时未操作timer
  timeout_timer: {
    timeout: 60 * 1000,
    timeoutObj: null,
    closeTimeObj: null,
    newTime: new Date().getTime(),
    oldTime: new Date().getTime(),
    outTime: 60 * 60 * 1000,
    // outTime: 6000,
    domEvent: function() {
      this.oldTime = new Date().getTime();
    },
    reset: function() {
      if (this.timeoutObj) {
        clearTimeout(this.timeoutObj);
      }
      if (this.closeTimeObj) {
        clearTimeout(this.closeTimeObj);
      }
      window.removeEventListener("click", this.domEvent);
      window.removeEventListener("mousemove", this.domEvent);
      return this;
    },
    start: function() {
      window.addEventListener("mousemove", this.domEvent);
      window.addEventListener("click", this.domEvent);
      this.timeoutObj = setTimeout(() => {
        this.newTime = new Date().getTime();
        if (this.newTime - this.oldTime > this.outTime) {
          socket.close();
          Vue.prototype
            .$confirm("由于您超时未操作,与服务器已断开连接", "提示", {
              confirmButtonText: "重新连接",
              cancelButtonText: "取消",
              type: "warning",
            })
            .then(() => {
              socket.reconnect();
              if (
                Vue.prototype.oldStatue &&
                Vue.prototype.oldStatue.classId &&
                Vue.prototype.oldStatue.data.pageId
              ) {
                let newStatus = {
                  classId: Vue.prototype.oldStatue.classId,
                  code: 101,
                  data: Object.assign(Vue.prototype.oldStatue.data, {
                    behavior: 8,
                  }),
                };
                socket.send(newStatus);
              }
              this.reset().start();
            })
            .catch(() => {});
        } else {
          this.reset().start();
        }
      }, this.timeout);
    },
  },
  /**
   * 初始化连接
   */
  init: (callback = null) => {
    if (!("WebSocket" in window)) {
      console.log("浏览器不支持WebSocket");
      alert("当前浏览器不支持监课室功能,请更换浏览器");
      return null;
    }
    if (!getToken()&&!localstorageGetToken()) {
      return null;
    }
    if (!store.getters.userInfo.id) {
      return null;
    }
    // 已经创建过连接不再重复创建
    if (socket.websock) {
      return socket.websock;
    }
    socket.ws_url = `${process.env.VUE_APP_BASE_API_WS}monitorRoom/${store.getters.userInfo.id}`;
    console.log(socket.ws_url);
    socket.websock = new WebSocket(socket.ws_url);
    socket.websock.onmessage = function(e) {
      socket.receive(e);
    };
    // 关闭连接
    socket.websock.onclose = function(e) {
      console.log("连接已断开");
      console.log("connection closed (" + e.code + ")");
      clearInterval(socket.hearbeat_interval);
      socket.socket_open = false;
      socket.timeout_timer.reset();
      socket.websock = null;
      // 需要重新连接
      if (socket.is_reonnect) {
        socket.reconnect_timer = setTimeout(() => {
          // 超过重连次数
          if (socket.reconnect_current > socket.reconnect_count) {
            clearTimeout(socket.reconnect_timer);
            return;
          }

          // 记录重连次数
          socket.reconnect_current++;
          socket.reconnect();
        }, socket.reconnect_interval);
      }
    };

    // 连接成功
    socket.websock.onopen = function() {
      console.log("连接成功", socket.ws_url);
      socket.socket_open = true;
      socket.is_reonnect = true;
      // 开启心跳
      socket.heartbeat();
      socket.timeout_timer.reset().start();
      if (callback) {
        callback();
      }
    };

    // 连接发生错误
    socket.websock.onerror = function() {
      console.log("WebSocket连接发生错误");
      socket.websock = null;
    };
  },

  /**
   * 发送消息
   * @param {*} data 发送数据
   * @param {*} callback 发送后的自定义回调函数
   */
  send: (data, callback = null) => {
    // 开启状态直接发送
    if (!socket.websock) {
      return;
    }
    if (socket.websock.readyState === socket.websock.OPEN) {
      console.log("发送消息：", JSON.stringify(data));
      socket.websock.send(JSON.stringify(data));

      if (callback) {
        callback();
      }

      // 正在开启状态，则等待1s后重新调用
    } else if (socket.websock.readyState === socket.websock.CONNECTING) {
      setTimeout(function() {
        socket.send(data, callback);
      }, 1000);

      // 未开启，则等待1s后重新调用
    } else {
      socket.init();
      setTimeout(function() {
        socket.send(data, callback);
      }, 1000);
    }
  },

  /**
   * 接收消息
   * @param {*} message 接收到的消息
   */
  receive: (message) => {
    var data = JSON.parse(message.data);

    if (data) {
      console.log("收到服务器内容：", message.data);
    }

    if (data == undefined) {
      console.log("收到服务器空内容");
      return false;
    }

    if (data.code == 551) {
      // 被服务器强制断开
      socket.socket_open = false;
      socket.is_reonnect = true;
      Vue.prototype
        .$confirm(
          "与服务器已断开连接，一台设备只能连接一个账号，请关闭其他页面后重新连接?",
          "提示",
          {
            confirmButtonText: "重新连接",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
        .then(() => {
          socket.reconnect();
        });
    } else if (data.code == 999) {
      // 心跳反馈
      console.log(999);
    } else if (data.code == 201) {
      // 收到推送题目
      console.log("收到推送题目", data.data);
    } else if (data.code == 251) {
      Vue.prototype.$alert("举手成功", "提示");
    } else if (data.code == 601) {
      Vue.prototype.$alert("举手失败,当前教师离线", "提示");
    } else if (data.code == 202) {
      // 收到推送文件
      console.log("收到推送文件", data.data);
    }
  },

  /**
   * 心跳
   */
  heartbeat: () => {
    if (socket.hearbeat_timer) {
      clearInterval(socket.hearbeat_timer);
    }
    socket.hearbeat_timer = setInterval(() => {
      var data = {
        code: 999,
      };
      socket.send(data);
    }, socket.hearbeat_interval);
  },
  /**
   * 超时未操作
   */
  timeout: () => {},
  /**
   * 主动关闭连接
   */
  close: () => {
    console.log("主动断开连接");
    clearInterval(socket.hearbeat_interval);
    socket.is_reonnect = false;
    socket.websock && socket.websock.close();
  },

  /**
   * 重新连接
   */
  reconnect: (callback = null) => {
    console.log("发起连接", socket.reconnect_current);
    if (socket.websock && socket.socket_open) {
      socket.websock.close();
    }
    socket.init(callback);
  },
};
export { socket };
